package com.blt.car.journey;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blt.car.R;
import com.blt.car.base.BaseTitleBarActivity;
import com.blt.car.base.ViewHolder;
import com.blt.car.utils.StringUtils;

import java.io.File;
import java.io.FileOutputStream;

import blt.app_core.api.base.CoreEvent;
import blt.app_core.api.base.CoreManager;
import blt.app_core.api.journey.JourneyApi;
import blt.app_core.api.journey.bean.AppealInfo;
import blt.app_core.api.journey.bean.ExtrasVo;
import blt.app_core.api.journey.bean.TravelDetail;
import blt.app_core.api.journey.bean.TravelOrder;
import blt.app_core.api.login.LoginApi;
import blt.app_core.api.other.OutApi;
import blt.app_core.log.Logger;
import blt.app_core.utils.UriProdiver;

import static com.blt.car.CarApp.getContext;

/**
 * Created by xgp on 2017/6/23.
 */

public class ExchangeComplaintActivity extends BaseTitleBarActivity {
    public static final String APPEAL_TYPE = "com.blt.car.journey.appeal_type";
    public static final int SUBMIT = 1 << 8;
    private int travelId;
    private int type;
    ExtrasVo vo;

    private TextView tvDay;
    private TextView tvAccount;
    private TextView tvExchangeNo;
    private EditText etspecification;
    private EditText etContactTel;
    private EditText etContactName;


    private Uri srcUri;
    public static final int SELECT_PIC_BY_TACK_CAMEAR = 4;
    public static final int SELECT_PIC_BY_PICK_PHOTO = 5;
    public static final int PHOTO_REQUEST_CUT = 6;
    private File tempFile;
    private String picPath;
    private ImageView mCover;


    public static void start(Context context, ExtrasVo extrasVo) {
        Intent intent = new Intent(context, ExchangeComplaintActivity.class);
        intent.putExtra(APPEAL_TYPE, extrasVo);
        context.startActivity(intent);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_exchange_comp;
    }


    @Override
    protected void initData() {
        super.initData();
        vo = (ExtrasVo) getIntent().getExtras().getSerializable(APPEAL_TYPE);
        if (vo.travel == null) {//修改时为空，需要请求
            CoreManager.getCore(JourneyApi.class).getDetail(vo.travelId);
        }

    }

    @Override
    protected void initView(ViewHolder holder) {
        mTitleBar.setTitle("交易申诉");
        holder.get(R.id.complaint_submit);
        tvDay = holder.get(R.id.exchange_happen_day);
        tvAccount = holder.get(R.id.exchange_fast_cost);
        tvExchangeNo = holder.get(R.id.exchange_exchange_no);
        etspecification = holder.get(R.id.exchange_specification);
        etContactTel = holder.get(R.id.exchange_contact_tel);
        etContactName = holder.get(R.id.exchange_contact_name);
        TravelOrder info = vo.travel;

        if (info != null) {
            setText(info);
        }

        holder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.complaint_submit) {
                    String content = etspecification.getText().toString();
                    String tel = etContactTel.getText().toString();
                    String name = etContactName.getText().toString();

                    if (vo.type == SUBMIT) {
                        //提交申诉
                        CoreManager.getCore(JourneyApi.class).addComplaint(UriProdiver.SUBMIT_COMPLAINT,
                                vo.travel.id,
                                content, null, null, null, name, tel, null);
                    }
                    {
                        //修改申诉
                        CoreManager.getCore(JourneyApi.class).addComplaint(UriProdiver.UPDATA_COMPLAINT,
                                travelId, content, null, null, null, name,
                                tel, null);
                    }

                } else if (v.getId() == R.id.exchange_complaint_upload) {
                    uploadPhoto();
                }

            }
        }, R.id.complaint_submit, R.id.exchange_complaint_upload);
    }

    @CoreEvent(coreClientClass = JourneyApi.class)
    public void onDetail(TravelDetail travelDetail) {
        setText(travelDetail.tbTravelOrder);
        travelId = travelDetail.tbTravelOrder.id;
    }

    @CoreEvent(coreClientClass = JourneyApi.class)
    public void onComplaintSuccess() {
        toastShort("提交成功");
        finish();
    }


    private void setText(TravelOrder order) {
        tvDay.setText(StringUtils.getHanZiDay(order.createTime));
        tvAccount.setText(order.amount + "元");
        tvExchangeNo.setText(order.orderNo);
        if (vo.appealInfo != null) {
            etspecification.setText(vo.appealInfo.appealDetail);
            etContactName.setText(vo.appealInfo.contact);
            etContactTel.setText(vo.appealInfo.phone);
        }
    }

    @CoreEvent(coreClientClass = OutApi.class)
    public void onUpload(String photoName) {
        if (TextUtils.isEmpty(photoName)) {
            toastShort("上传失败");
            return;
        }
        toastShort("上传成功");
    }


    private void uploadPhoto() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("上传照片");
        builder.setItems(new String[]{"相册", "拍照"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        takePhoto();
                        break;
                    case 1:
                        takeCamera();
                        break;
                }
            }
        });
        builder.create();
        builder.show();
    }

    private void takeCamera() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        tempFile = new File(Environment.getExternalStorageDirectory(),
                "temp_photo.jpg");

        // 从文件中创建uri
        Uri uri = Uri.fromFile(tempFile);
        srcUri = Uri.fromFile(tempFile);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(openCameraIntent, SELECT_PIC_BY_TACK_CAMEAR);
    }

    private void takePhoto() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK, srcUri);
        pickIntent.setDataAndType(srcUri, "image/*");
        startActivityForResult(pickIntent, SELECT_PIC_BY_PICK_PHOTO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    showHead(uri);
                } else {
                    Bundle bandle = data.getExtras();
                    if (bandle != null) {
                        Bitmap bitmap = (Bitmap) bandle.get("data");
                        if (bitmap != null) {
//                            if (uploadType == 100) {
//                                mCover.setVisibility(View.VISIBLE);
//                                mCover.setImageBitmap(bitmap);
//                            }
                        }
                    } else {
                        if (srcUri != null) {
                            //showHead(tempUri);
                            picPath = tempFile.getPath();
                            picPath = srcUri.getPath();
                            Bitmap bitmap = null;//BitmapFactory.decodeFile(picPath);
                            if (picPath != null) {
                                bitmap = BitmapFactory.decodeFile(picPath);
                            }
                            crop(srcUri);
                        }
                    }
                }
            } else {

                if (tempFile != null) {
                    picPath = tempFile.getPath();
                    Bitmap bitmap = BitmapFactory.decodeFile(picPath);
                    crop(Uri.fromFile(tempFile));
                }
            }
            if (requestCode == PHOTO_REQUEST_CUT) {
                Bitmap bitmap = null;
                if (srcUri != null) {
                    picPath = srcUri.getPath();
                    if (picPath != null) {
                        bitmap = BitmapFactory.decodeFile(picPath);
                    }
                }
                if (bitmap != null) {
//                    userService.updateHead(getBitmapPath(bitmap));
                    Logger.d("picPath:" + picPath);
                    CoreManager.getCore(OutApi.class).uploadFile(picPath);
                    mCover.setImageBitmap(bitmap);
                }
            }
        }
    }


    //返回显示头像
    private void showHead(Uri uri) {
        String[] pojo = {MediaStore.MediaColumns.DATA};
        Cursor cursor = getContentResolver().query(uri, pojo, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            picPath = cursor.getString(columnIndex);
            // 4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
            if (Build.VERSION.SDK_INT < 14) {
                cursor.close();
            }
        } else {
            if (uri != null) {
                picPath = uri.getPath();
            }
        }
        if (picPath != null) {
            BitmapFactory.Options option = new BitmapFactory.Options();
            option.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(picPath, option);

            option.inSampleSize = computeSampleSize(option, -1, 128 * 128);
            option.inJustDecodeBounds = false;
            try {
                Bitmap bm = BitmapFactory.decodeFile(picPath, option);

                String fileName = "temp.png";
                String filePath = getContext().getFilesDir().getAbsolutePath();
                File f = new File(filePath, fileName);
                int tryTimes = 5;
                while (f.exists() && tryTimes > 0) {
                    f.delete();
                    --tryTimes;
                }
                try {
                    FileOutputStream out = new FileOutputStream(f);
                    bm.compress(Bitmap.CompressFormat.PNG, 0, out);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                }

                // 显示在图片控件上
//                if (uploadType == 100) {
//                    mCover.setVisibility(View.VISIBLE);
//                    mCover.setImageBitmap(bm);
//                }

                CoreManager.getCore(OutApi.class).uploadFile(picPath);
//                userService.updateHead(filePath + "/" + fileName);//(picPath);
            } catch (OutOfMemoryError err) {
//                MLog.error(TAG, "android java.lang.OutOfMemoryError");
            } catch (NullPointerException e) {
//                MLog.error(TAG, e.toString());
            }
        }
    }

    private void crop(Uri uri) {
        final int dp = 128;

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        intent.putExtra("aspectX", 1);//输出是X方向的比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", dp);//输出X方向的像素
        intent.putExtra("outputY", dp);
        intent.putExtra("outputFormat", "PNG");
        intent.putExtra("noFaceDetection", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, srcUri);
        intent.putExtra("return-data", false);//设置为不返回数据

        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }


    public static int computeSampleSize(BitmapFactory.Options options,
                                        int minSideLength, int maxNumOfPixels) {
        int initialSize = computeInitialSampleSize(options, minSideLength,
                maxNumOfPixels);

        int roundedSize;
        if (initialSize <= 8) {
            roundedSize = 1;
            while (roundedSize < initialSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (initialSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    private static int computeInitialSampleSize(BitmapFactory.Options options,
                                                int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 :
                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 :
                (int) Math.min(Math.floor(w / minSideLength),
                        Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) &&
                (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }


}
